<template>
  <u-upload
    :fileList="fileList"
    @afterRead="afterRead"
    :width="width"
    :height="height"
    @delete="deletePic"
    name="1"
    :multiple="multiple"
    :maxCount="maxCount"
  >
    <template v-if="!$slots.slot">
      <view class="view">
        <u-icon name="camera-fill" color="#aeaeaf" size="56"></u-icon>
        <view class="tip">{{ tip }}</view>
      </view>
    </template>

    <slot name="slot"></slot>
  </u-upload>
</template>

<script>
import config from "@/utils/config";
import { getToken } from "@/utils/auth";
export default {
  props: {
    tip: String,
    maxCount: {
      type: [String, Number],
      default: 1,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    height: {
      type: String,
      default: "206rpx",
    },
    width: {
      type: String,
      default: "206rpx",
    },
  },
  data() {
    return {
      fileList: [],
    };
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this.fileList.splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this.fileList.length;
      lists.map((item) => {
        this.fileList.push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this.fileList[fileListLen];
        this.fileList.splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result,
          })
        );
        fileListLen++;
        this.$emit("change", item, this.fileList);
        this.$emit("input", this.fileList.map((item) => item.url).toString());
      }
    },
    uploadFilePromise(url) {
      console.log(getToken());
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: `${config.APP_BASE_URL}/common/upload`, // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          formData: {},
          header: {
            Authorization: "Bearer " + getToken(),
          },
          success: (res) => {
            resolve(JSON.parse(res.data).url);
          },
        });
      });
    },
  },
};
</script>
<style lang="less" scoped>
.view {
  width: 206rpx;
  height: 206rpx;
  background: #f7f7f7;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.tip {
  font-size: 30rpx;
  color: #2e2528;
  margin-top: 28rpx;
}
</style>
